import fs from 'fs';
import { fileURLToPath } from 'url';

//暴露 查找所有控制器包下的所有以Controller.js结尾的文件
export const queryAllController = () => {

    //可被浏览器解析的controller包目录
    let ctrlPathFile = new URL('../controller', import.meta.url).href
    // console.log(ctrlPathFile);

    //转换成绝对路径
    let ctrlPath = fileURLToPath(ctrlPathFile);
    // console.log(ctrlPath);

    //读取ctrlPath包下的所有控制器文件
    let AllJs = fs.readdirSync(ctrlPath)
    // console.log(AllJs);

    //过滤 只拿Controller.js结尾的文件
    let ctrlAllJs = AllJs.filter(file => file.endsWith('Controller.js')).map(item => `${ctrlPathFile}/${item}`)
    // console.log(ctrlAllJs);

    return ctrlAllJs;
}

//暴露 注册路由
export const registerRouter = (router, ctrlAllJs) => {

    //读控制器文件并拿到定义好的路由对象
    ctrlAllJs.forEach(async item => {
        const { users } = await import(item)
        // console.log(users);

        //遍历数组
        users.forEach(user => {
            //拿到路由对象里的请求方法,请求路径以及所对应的方法
            let reqMethod = user.method;
            let reqPath = user.path;
            let reqFn = user.fn;
            // console.log(reqMethod);
            // console.log(reqPath);
            // console.log(reqFn);

            //注册路由
            if (reqMethod === "GET") {
                router.get(reqPath, reqFn)
            }
            if (reqMethod === "POST") {
                router.post(reqPath, reqFn)
            }
            if (reqMethod === "DELETE") {
                router.delete(reqPath, reqFn)
            }
            if (reqMethod === "PUT") {
                router.put(reqPath, reqFn)
            }
        })

    });

}